package com.zyk.scaffold.tcp.server.channel;

import com.zyk.scaffold.tcp.enums.HeartBeatTypeEnum;
import com.zyk.scaffold.tcp.holder.ContextHolder;
import com.zyk.scaffold.tcp.propertises.TcpProperties;
import com.zyk.scaffold.tcp.proto3.MessageBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

@ChannelHandler.Sharable
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        TcpProperties tcpProperties = ContextHolder.getTcpProperties();
        ChannelPipeline pipeline = socketChannel.pipeline();
        boolean ackHeartBeat = HeartBeatTypeEnum.ACK.equals(HeartBeatTypeEnum.converter(tcpProperties.getServer().getHeartBeatType()));
        if(ackHeartBeat){
            // 心跳
            pipeline.addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS));
        }
        // 解码
        pipeline.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
        pipeline.addLast("decoder", new ProtobufDecoder(MessageBuf.JMTransfer.getDefaultInstance()));
        // 解码
        pipeline.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
        pipeline.addLast("encoder", new ProtobufEncoder());
        if(ackHeartBeat){
            // 心跳事件
            pipeline.addLast(new ServerIdleStateTrigger(ContextHolder.getTcpConnectionManager()));
        }
        // 处理
        pipeline.addLast("handler", new TcpServerHandler(
                ContextHolder.getTcpProperties(),
                ContextHolder.getSessionManager(),
                ContextHolder.getTcpConnectionManager())
        );
    }
}
